package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

// 创建一个结构体
type Student struct {
	Name string
	Age  int
}

var clientl *mongo.Client

func initlDB() {
	//设置客户端
	co := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
	//连接
	var err error //error 默认为nil
	c, err := mongo.Connect(context.TODO(), co)
	if err != nil {
		log.Fatal(err)
	}
	//检查连接
	err = c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connected to MongoDB!")
	clientl = c
}

// 添加单个文档 ,使用collection.InsertOne()方法插入一条文档记录：
func insertOne(s Student) {
	initlDB()
	collection := clientl.Database("go_db").Collection("student")
	insertResult, err := collection.InsertOne(context.TODO(), s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Inserted a single document:", insertResult)
}

// 插入多个文档,使用collection.InsertMany()方法插入多条文档记录
func insertMany(s []interface{}) {
	initlDB()
	collection := clientl.Database("go_db").Collection("student")
	insertManyResult, err := collection.InsertMany(context.TODO(), s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Inserted muliple documents:", insertManyResult.InsertedIDs)
}

func main() {
	//单条
	s := Student{Name: "tom", Age: 20}
	insertOne(s)

	//多条
	s1 := Student{Name: "jerry", Age: 18}
	s2 := Student{Name: "marry", Age: 23}
	s3 := Student{Name: "bao", Age: 17}
	students := []interface{}{s1, s2, s3}
	insertMany(students)
}
